package com.travelpass.fragments;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.travelpass.R;
import com.travelpass.slidingMenu.MainActivity;

@SuppressLint("ValidFragment")
public class HorairesVol extends SherlockFragment {

	private View view;

	Spinner dep, arr;

	String depart = "CASABLANCA", arrivee = "CASABLANCA";

	LinearLayout vol;

	public HorairesVol() {

	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.horairesvol, container, false);

		init();
		return view;

	}

	private void init() {
		dep = (Spinner) view.findViewById(R.id.dep);
		arr = (Spinner) view.findViewById(R.id.arr);
		MainActivity.villes = new ArrayList<String>();

		MainActivity.villes.add("CASABLANCA");
		MainActivity.villes.add("FES");
		MainActivity.villes.add("OUJDA");
		MainActivity.villes.add("MARRAKECH");
		MainActivity.villes.add("TANGER");
		MainActivity.villes.add("RABAT");
		MainActivity.villes.add("AGADIR");
		MainActivity.villes.add("NADOR");
		MainActivity.villes.add("DAKHLA");
		MainActivity.villes.add("ESSAOUIRA");
		MainActivity.villes.add("HOCEIMA");
		MainActivity.villes.add("OUARZAZATE");

		MyAdapter adapter = new MyAdapter(MainActivity.villes);
		dep.setAdapter(adapter);
		arr.setAdapter(adapter);

		dep.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				depart = (String) parent.getItemAtPosition(pos);
			}

			public void onNothingSelected(AdapterView parent) {
				// Do nothing.
			}
		});

		arr.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			/**
			 * Called when a new item was selected (in the Spinner)
			 */
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				arrivee = (String) parent.getItemAtPosition(pos);
			}

			public void onNothingSelected(AdapterView parent) {
				// Do nothing.
			}
		});

		((Button) view.findViewById(R.id.trouver)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (depart.equals(arrivee)) {
					Toast.makeText(getActivity(), "Selectionner deux villes differentes", Toast.LENGTH_SHORT).show();
				} else
					new GetHoraires(depart, arrivee).execute();
			}
		});
		vol = (LinearLayout) view.findViewById(R.id.voll);
	}

	private class GetHoraires extends AsyncTask<Void, Void, Void> {

		ProgressDialog progress;
		String v1, v2, json;

		public GetHoraires(String a, String b) {
			v1 = a;
			v2 = b;
		}

		@Override
		protected void onPreExecute() {
			progress = ProgressDialog.show(getActivity(), "", "Chargement...", true);
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				DefaultHttpClient client = new DefaultHttpClient();

				String link = "http://192.168.1.145:8080/TravelServer2/travelservice/findfly/" + v1 + "/" + v2;
				System.out.println(link);
				HttpGet post = new HttpGet(link);

				HttpResponse resp = client.execute(post);

				HttpEntity entity = resp.getEntity();
				InputStream ws = entity.getContent();

				BufferedReader r = new BufferedReader(new InputStreamReader(ws, "iso-8859-1"), 8);
				StringBuilder b = new StringBuilder();
				String line = null;
				while ((line = r.readLine()) != null) {
					b.append(line + "\n");
				}

				ws.close();
				json = b.toString();

			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

			try {
				JSONObject jsonObject = new JSONObject(json);
				JSONObject header = jsonObject.getJSONObject("header");
				if (header.getString("status").equals("OK")) {
					JSONObject jsonObject2 = jsonObject.getJSONObject("response");
					((LinearLayout) view.findViewById(R.id.select)).setVisibility(View.GONE);
					((LinearLayout) view.findViewById(R.id.content)).setVisibility(View.VISIBLE);
					((TextView) view.findViewById(R.id.titre)).setText("Trajet: " + depart + " -> " + arrivee);

					JSONArray horairesavion = jsonObject2.getJSONArray("horairesavion");
					for (int i = 0; i < horairesavion.length(); i++) {

						JSONObject jsonObject3 = horairesavion.getJSONObject(i);
						View v = LayoutInflater.from(getActivity()).inflate(R.layout.vol, null);
						((TextView) v.findViewById(R.id.dep)).setText(jsonObject3.getString("depart"));
						((TextView) v.findViewById(R.id.vol)).setText(jsonObject3.getString("vols"));
						((TextView) v.findViewById(R.id.com)).setText(jsonObject3.getString("compagnie"));
						((TextView) v.findViewById(R.id.via)).setText(jsonObject3.getString("via"));
						((TextView) v.findViewById(R.id.etat)).setText(jsonObject3.getString("etat"));
						((TextView) view.findViewById(R.id.date)).setText("Date: " + jsonObject3.getString("date"));
						vol.addView(v);
					}

				} else {
					((TextView) view.findViewById(R.id.msg)).setVisibility(View.VISIBLE);
					((TextView) view.findViewById(R.id.msg)).setText(header.getString("message"));
				}
			} catch (Exception e) {
				Toast.makeText(getActivity(), "Une erreur s'est produite", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			}
			if (progress.isShowing())
				progress.dismiss();
			super.onPostExecute(result);
		}
	}

	private class MyAdapter extends BaseAdapter implements SpinnerAdapter {

		/**
		 * The internal data (the ArrayList with the Objects).
		 */
		private final List<String> data;

		public MyAdapter(List<String> data) {
			this.data = data;
		}

		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public Object getItem(int position) {
			return data.get(position);
		}

		@Override
		public long getItemId(int i) {
			return i;
		}

		@Override
		public View getView(int position, View recycle, ViewGroup parent) {
			TextView text;
			if (recycle != null) {
				// Re-use the recycled view here!
				text = (TextView) recycle;
			} else {
				// No recycled view, inflate the "original" from the platform:
				text = (TextView) getActivity().getLayoutInflater().inflate(android.R.layout.simple_dropdown_item_1line, parent, false);
			}
			text.setTextColor(Color.BLACK);
			text.setText(data.get(position));
			return text;
		}

	}

}
